/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: AudioServer.cpp,v 1.3 2009-10-21 14:58:55 morsko Exp $
 *
 * \file
 * \brief Implementation of Audio interface Server.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */
#include "AudioServer.hpp"
#include "AudioData.hpp"

//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
using namespace MaCI::Audio;
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
CAudioServer::CAudioServer(MaCICtrl::CMaCICtrlServer *aMaCICtrlServerPtr, 
                   const int aInterfaceMinor,
                   const std::string &aDescription,
                   const std::string &aInstanceName)
  : CMaCI(aMaCICtrlServerPtr, GIMI_PROTOCOL_MACI_AUDIO, aInterfaceMinor, aInstanceName),
    CSync(1,1),
    CThread(1),
    iServerActive(false),
    iAudioInfo(),
    iAudioInfoSet(false),
    iAudioSequenceNumber(0),
    iServiceDescription(aDescription)
{
  SetInterfaceSubscriberSyncLimits(1,1000);
}
//*****************************************************************************
CAudioServer::~CAudioServer()
{
  DoClose();
}
//***************************************************************************** 

MaCI::EMaCIError CAudioServer::DoOpen(void)
{
  EMaCIError result = KMaCIError;
  assert(this != NULL);
  assert(iGIMIPtr != NULL);
  
  // Execute only if server is not active.
  if (!iServerActive && iAudioInfoSet) {
    // Register service.
    RegisterProvidedService("MaCI-AudioServer; '" + iServiceDescription + "'");
    RegisterAcceptedService("MaCI-AudioServer-Cmd; '" + iServiceDescription + "'");
    
    // Start the handler Thread
    iServerActive = true;
    CThread::RunThread();
    
    result = KMaCIOK;
    
    dPrint(4,"Succesfully Open():ed AudioServer instance %p.", this);
  }else{
    if(iServerActive){
      dPrint(5,"Server already opened");
    }

    if(!iAudioInfoSet){
      dPrint(3,"Audio info hasn't been set, please set it before opening audioserver");
    }
  }
    
  return result;
}
//*****************************************************************************      
   
MaCI::EMaCIError CAudioServer::DoClose(void)
{
  EMaCIError result = KMaCIError;
  assert(this != NULL);
  assert(iGIMIPtr != NULL);

  // Execute block only if server is currently active.
  if (iServerActive) {
    // Stop!
    iServerActive = false;

    // Stop the handler Thread
    iServerActive = false;
    /* CThread::CancelThread(); //Removed by script */
    CThread::WaitThread();    

    // Unregister services
    UnregisterProvidedService();
    UnregisterAcceptedService();
    
    dPrint(4,"Succesfully Close():ed AudioServer instance %p", this);
  }
  
  return result;
}
//*****************************************************************************      

MaCI::EMaCIError CAudioServer::SendAudioData(const CAudioData &aAudioData)
{
  EMaCIError result = KMaCIError;

  if (iServerActive) {

    // Update sequence.
    ++iAudioSequenceNumber;
    SendInterfaceSubscriberMessage(aAudioData.GetBinBagContainerPtr()->GetBuffer(),
                                   aAudioData.GetBinBagContainerPtr()->GetBufferSize(),
                                   iAudioSequenceNumber);
    dPrint(1,"SendInterfaceSubscriberMessage called: %d:%d, seq: %d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             iAudioSequenceNumber,
             aAudioData.GetBinBagContainerPtr()->GetBufferSize());
    // Result
      result = KMaCIOK;

  } else {
    dPrint(2,"Unable to send AudioData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }

  return result;

}
//*****************************************************************************
void CAudioServer::SetAudioInfo(TAudioInfo &aAudioInfo)
{
  iAudioInfo = aAudioInfo;
  iAudioInfoSet = true;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
void CAudioServer::ProcessMessage(const gimi::GIMIMessage &msg)
{
  
  gim::binbag::CBinBag bb;
  CAudioData d;
  bool r;
  
  // Before even attempting to decode, read access.
  /*  MaCICtrl::TAccess a;
  CMaCI::GetMaCICtrlServer()->GetAccessInfo(a, 
                                            iInterfaceMajor,
                                            iInterfaceMinor,
                                            msg.getSenderId(),
                                            true);
  
  // Test for access.
  if (a.IsAccess()) {
    dPrint(8,"Access granted for nodeID: %08X, proceed with command.",
           msg.getSenderId());
  */
    r = bb.Decode(msg.getData(), msg.getDatalength());
    if (r) {
      // Succesfully decoded as BinBag.
      r = d.DecodeFrom(&bb);
      if (r) {
        // Succesfully decoded as SpeedCtrl
        // Now, Check whether it was Command, if so, process it and construct reply
        gim::binbag::CBinBag replybb;
        CAudioData reply;
        bool send_reply = false;

        // Do encoding to this binbag
        reply.EncodeTo(&replybb);
      
        const TCommand *cmd = d.GetCommand();
        if (cmd) {
          switch(cmd->cmd) {
          
            // Set Commands: by default passed to user
          case  KCommandGetAudioInfo:
            dPrint(1,"Got message Get Audio info");
            Lock();
            reply.SetCommand(TCommand( KCommandGetAudioInfoReply));
            reply.SetTimestamp(Common::TTimestamp());
            
            reply.SetAudioInfo((const TAudioInfo)iAudioInfo);

            Unlock();
            send_reply = true;
            break;

          case KCommandNewAudio:
            dPrint(4,"Nothing to do on CommandNewAudio :)");
            break;
            
          default:
            dPrint(4,"Unidentified command! %d (%x)! Ignore.",
                   cmd->cmd, cmd->cmd);
            break;
          }
        }
        
        // Check whether reply needs to be sent
        if (send_reply) {
          dPrint(1,"Sending reply with id %u",msg.messageId);
          bool result = SendSynchronousMessageReply(replybb.GetBuffer(),
                                                    replybb.GetBufferSize(),
                                                    msg.getSenderId(),
                                                    iInterfaceMajor,
                                                    iInterfaceMinor,
                                                    msg.messageId);
          if (result) {
            dPrint(1,"Succesfully sent message with %d BinBag elements to '%p'",
                   replybb.GetElementCount(),
                   msg.getSenderId());

          } else {
	  
            dPrint(1,"Failed to send message with %d BinBag elements to '%p'",
                   replybb.GetElementCount(),
                   msg.getSenderId());
          }
        }
      }
    }
    /* } else {
    dPrint(2,"Access denied for nodeID: %08X, will not execute command.",
           msg.getSenderId());
    
           }  */
 
}
//*****************************************************************************

int CAudioServer::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(iServerActive) {
    // Call the ReceiveMessage wrapper with 2s timeout
    e = ReceiveInterfaceMessage(gmsg, 2000);
    if (e == KMaCIOK) {
      dPrint(1,"Got GIMIMessage %d - Processing.", gmsg.messageId);
      ProcessMessage(gmsg);
      
    } else if (e != KMaCITimeout) {
      // Other error, try to recover by sleeping one second.
      ownSleep_ms(1000);
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");

  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
